/**
 * @author klv
 */

var QS_simpleWatchlist=function(container,config,callback){
	this.profile={
		isAPI:true,
		fixHeight:true,
		
		//grid config
		remove:false,//if the grid display the remove column
		sortable:true,
        cellResize:false,
        viewText:false,
        viewTextTab:[],
        viewTextKey:'euambottomtext',
        cellRearrange:false,
        highlightColumn:false,
        isFormat:false,
        needUnit:false,
        numberSeparate:"",
		rowDragable: false,
		rowDropable: false,
		groupBy:'st152',//default group by sector
		viewKey:["LastPrice","Chg","Chg%"],//grid columns
		
		//layout config
		showLayout:true,
		layoutData:[//layout selectable list
			{txt: QS_Lang.watchlist['list'],val: 'list'},
			{txt: QS_Lang.watchlist['heatmap'],val: 'heatmap'}
		],
		layoutContainer:$("body"),//layout container
		displayLayout:'list',//default layout
		
		//tabmenu config
		showTab:true,
		openedList: [],//tabmenu list(only val array)
		defaultWatchlist:-1,//default active/open watchlist
		tabclosable:false
	};
	this.staticValue={
		tabMenuHeight:28,
		bottomTextHeight:20,
		winTitle:26,
		minWidth:200
	};
	this.container=container;
	this.el=null;
	this.tab=null;
	this.holdingId=-10000;
	this.commonColumns=false;//tag tickerlist colnumns
	this.bottomTextShow = false;
	this.layout=null;
	this.cacheWL={};//cache watchlist data
	$.extend(true,this.profile,config);
	this.tabID=this.profile.defaultWatchlist;
	this.callback={};
	$.extend(true,this.callback,callback);
	this._createTickerList();
};
QS_simpleWatchlist.prototype={
	_appendBottomText:function(tabid){
		if(this.profile.viewText){
			var bottomdom=this.el.find(".rtq-wl-bottomtext");
			if(!this.bottomTextShow&&(this.profile.viewTextTab.length==0||$.inArray(tabid,this.profile.viewTextTab)!=-1)){
				this.bottomTextShow=true;
				this.changeOutSize(this.el.width(),this.el.height());
				bottomdom.show();
			}else if(this.profile.viewTextTab.length>0&&$.inArray(tabid,this.profile.viewTextTab)==-1&&this.bottomTextShow){
				this.bottomTextShow=false;
				this.changeOutSize(this.el.width(),this.el.height());
				bottomdom.hide();
			}
		}
	},
	_createTickerList:function(){
		var self=this,html='<div class="rtq-simpleWL"><div class="rtq-wl-tab-wrap clearfix"></div><div class="rtq-wl-wrap"></div>'+(this.profile.viewText?('<div class="rtq-wl-bottomtext">'+QS_Lang.watchlist[this.profile.viewTextKey]||''+'</div>'):'')+'</div>';
		this.el=$(html).appendTo(this.container);
		var tickerlistConfig={
			displayLayout:this.profile.displayLayout,
			groupBy:this.profile.displayLayout.indexOf('group') > -1?this.profile.groupBy : null,
			autoHeight:this.profile.fixHeight?false:true,
			remove:this.profile.remove,
			rowDragable: this.profile.rowDragable,
			rowDropable: this.profile.rowDropable,
			sortable:this.profile.sortable,
			cellResize:this.profile.cellResize,
			cellRearrange:this.profile.cellRearrange,
			highlightColumn:this.profile.highlightColumn,
			viewKey:this.profile.viewKey,
			isFormat:this.profile.isFormat,
			isUnit:this.profile.needUnit,
        	numberSeparate:this.profile.numberSeparate
		},tickerCallback={
			onLoad:function(para){
                if(typeof self.callback.onLoad=='function'){
                    self.callback.onLoad({
						component: "watchlist",
						height: para.height+(self.profile.showTab?self.staticValue.tabMenuHeight:0)+(self.bottomTextShow?self.staticValue.bottomTextHeight:0),
						width: para.width,
						minWidth : para.minWidth
					});
                }
            },
            onRowDoubleClick:function(e,row){
            	 if(typeof self.callback.onRowDoubleClick=='function'){
            	 	var pid=null;
            	 	if(!row.data.pid&&gData){
            	 		pid = gData[row.data.gkey].performanceId;
            	 	}
                    self.callback.onRowDoubleClick({
                    	ticker: row.data.Symbol, //Symbol,gkey,id,pid
	                    pid: pid,
						component: "watchlist"
					});
                }
			},
			onRowSelected:function(e,row){
            	 if(typeof self.callback.onTickerClick=='function'){
            	 	var pid=row.data.pid;
            	 	if(!row.data.pid&&gData){
            	 		pid = gData[row.data.gkey].performanceId;
            	 	}
                    self.callback.onTickerClick({
                    	ticker: row.data.Symbol, //Symbol,gkey,id,pid
	                    pid: pid,
						component: "watchlist"
					});
                }
			},
            onHeightChange:function(para){
                if(typeof self.callback.onHeightChange=='function'){
                    self.callback.onHeightChange({
						component: "watchlist",
						height: para.height+(self.profile.showTab?self.staticValue.tabMenuHeight:0)+(self.bottomTextShow?self.staticValue.bottomTextHeight:0),
						width: para.width
					});
                }
            }
		};
		if(this.profile.headMapCols){
			tickerlistConfig.headMapCols=this.profile.headMapCols;
		}
		if(this.profile.width){
			tickerlistConfig.width=this.profile.width;
			this.el.css({width:this.profile.width});
		}else{
			tickerlistConfig.width=this.profile.initwidth;
		}
		if(this.profile.height){
			tickerlistConfig.height=this.profile.height-(this.profile.showTab?this.staticValue.tabMenuHeight:0);
			this.el.css({height:this.profile.height});
		}else{
			tickerlistConfig.height=this.profile.initheight-(this.profile.showTab?this.staticValue.tabMenuHeight:0);
		}
		this.tickerlist=new QS_tickerList(this.el.find(".rtq-wl-wrap"),tickerlistConfig,tickerCallback);
		this.commonColumns=true;
	},
	init:function(){
		var self=this;
		if(this.profile.width){
			this.el.css({width:this.profile.width});
		}
		if(!this.profile.isAPI&&!isNaN(this.profile.height)){
            this.profile.height-=this.staticValue.winTitle;
        }  
		if(this._existDB()){
			this._getDBWLlist(function(){
				self._bindData();
			})
		}else{
			this._bindData();
		}
	},
	setTickerValidation:function(tickerValidation){
		this.tickerlist.tValidation = tickerValidation;
	},
	_existDB:function(){
		var len=this.profile.openedList.length;
		if(len==0){this.profile.openedList.push(this.profile.defaultWatchlist);len=1;}
		if(typeof MstarData!='undefined'){
			for(var i=0,l=len;i<l;i++){
				if(!MstarData.Watchlist[this.profile.openedList[i]]) return true;
			}
		}else{
			return true;
		}
		return false;
	},
	acceptTicker:function(tickers){  //
        this.tickerlist.addTickers(tickers);
    },
	_bindData:function(){
		var tabContainer=this.el.find(".rtq-wl-tab-wrap"),self=this;
		//bind tabmenu
		var tabData=this._getTabData();
		if(this.profile.showTab){
			this.tab = new Util.TabMenu(this.profile.tabContainer?this.profile.tabContainer:tabContainer, tabData, {
                    onActive: function(tab){
						self.tabID=tab.id;
						self._appendBottomText(tab.id);
						self.tickerlist.setWatchlistId(tab.id);
						self._getTickers(self.tabID,function(holdings){
							self.tickerlist.setDecimal(tab.decimal);
							self.tickerlist.reBindData(holdings);
						});
                    },
					onDeActive: function(tab){
						self.tickerlist.stopSubscribe();
					}
                }, {
                    width: 80,
                    tabsList: false,
					isExcuteCallbackAtInit: true,
					activeTabId:this.tabID,
					plusSymbol:false,
                    rearrange: false
                });
		}else{
			tabContainer.hide();
			this._appendBottomText(this.tabID);
			this._getTickers(this.tabID,function(holdings){
				self.tickerlist.setDecimal(tabData[0].decimal);
				self.tickerlist.reBindData(holdings);
			});
		}
		this.staticValue.tabMenuHeight = tabContainer.height();
		//bind layout
		if(this.profile.showLayout){
			this.layout = new Util.DropDownList(this.profile.layoutContainer, function(t, v){
					if (self.layout != v) {
						self.layout=v;
						if(v.indexOf("group")>0){
							self.tickerlist.groupBy(self.profile.groupBy);
						}
						if(self.profile[v+"_viewKey"]){
							self.commonColumns = false;
							self.tickerlist.setColumnsByKeys(self.profile[v+"_viewKey"]);
						}else if(!self.commonColumns){
							self.commonColumns = true;
							self.tickerlist.setColumnsByKeys(self.profile["viewKey"]);
						}
						self.tickerlist.changeViewType(v);
					}
				},this.profile.layoutData,{
					width: 150,
					actionAtInit:false
			});
			this.layout.setTextValue(null, this.profile.displayLayout);
		}
	},
	_getDefaultWL:function(watchlistID,watchlistinfo,callback){
		var self=this;
		DBHelper.getDefaultTickersByWatchId(watchlistID,function(data){
			if(data&&data!="error"){
				var jTickerData = $.evalJSON(data),holdings=[];
				if(jTickerData&&jTickerData.tickers){
					var tickers=jTickerData.tickers;
					self.cacheWL[watchlistID].tickers=tickers;
					if(watchlistinfo.securityType){//only support future in DB
						self._getCommodity(tickers,function(Holdings){
							self._getHoldingsCallback(watchlistID,Holdings,callback);
						});
					}else{
						for(var i=0,l=tickers.length;i<l;i++){
							holdings.push({
								HldgId: self.holdingId--,
								SecId: tickers[i],
								Rank: i + 1
							});
						}
						self._getHoldingsCallback(watchlistID,holdings,callback);
					}
				}
			}
		});
	},
	_getCommodity:function(rootTickers,callback){
		var self=this;
		DBHelper.getCommodity("Overview",function(data){
			var holdings=[];
			if (data != null && data != '') {
				var jData = $.evalJSON(data);
				var symbols=jData.Overview;
				var s=null;
				for(var j=0,len=rootTickers.length;j<len;j++){
					s=symbols[rootTickers[j]];
					if(s){
						var details=s.Details;
						var feedSrcId=s.FeedSrcId;
						var exch=s.Exch||'';
						var name=s.Name||'';
						var idx=name.indexOf('Cont.');
						if(idx>-1){
							name=name.substring(0,idx);
						}   
						if(!details||!feedSrcId){
							continue;
						}
						if(typeof QS_FuturesMap=='undefined'){
							QS_FuturesMap={};
						}
						QS_FuturesMap[rootTickers[j]]=[name,exch];
						var symbol=null;
						for(var i=0,l=details.length;i<l;i++){
							symbol=details[i][0];
							if(symbol.substring(symbol.length-1,symbol.length)!='Y'){
								holdings.push({
									HldgId: self.holdingId--,
									SecId: "/"+feedSrcId+":"+symbol,
									Rank: i + 1
								});
								break;
							}
						}
					}else{
						holdings.push({
							HldgId: self.holdingId--,
							SecId: rootTickers[j],
							Rank: i + 1
						});
					}
				}
				callback(holdings);
			}else{
				callback(holdings);
			}
		});
	},
	_getTickers:function(watchlistID,callback){
		var self=this,watchlistinfo=this.cacheWL[watchlistID]?this.cacheWL[watchlistID]:this._getWatchlistInfo(watchlistID);
		if(watchlistinfo.holdings){
			callback(watchlistinfo.holdings);
		}else if(watchlistinfo.inDB){
			this._getDefaultWL(watchlistID,watchlistinfo,callback);
		}else if(watchlistinfo.tickers){//include ticker
			var tickers=watchlistinfo.tickers,holdings=[];
			for(var i=0,l=tickers.length;i<l;i++){
				holdings.push({
					HldgId: self.holdingId--,
					SecId: tickers[i],
					Rank: i + 1
				});
			}
			if(watchlistinfo.externalTickerValidation){
				watchlistinfo.externalTickerValidation.checkTickers(holdings,function(validHoldings){
					self._getHoldingsCallback(watchlistID,self._addHoldingID(validHoldings),callback);
				});
			}else{
				self._getHoldingsCallback(watchlistID,self._addHoldingID(holdings),callback);
			}
		}else{
			if(watchlistinfo.externalDataSource){
				watchlistinfo.externalDataSource(watchlistinfo.args,function(holdings){//external datasouce
					if(watchlistinfo.externalTickerValidation){
						watchlistinfo.externalTickerValidation.checkTickers(holdings,function(validHoldings){
							self._getHoldingsCallback(watchlistID,self._addHoldingID(validHoldings),callback);
						});
					}else{
						self._getHoldingsCallback(watchlistID,self._addHoldingID(holdings),callback);
					}
				});
			}
		}
	},
	_addHoldingID:function(holdings){
		//HldgId
		for(var i=0,l=holdings.length;i<l;i++){
			holdings[i].HldgId=this.holdingId--;
		}
		return holdings;
	},
	_getHoldingsCallback:function(wlID,holdings,callback){
		this.cacheWL[wlID].holdings=holdings;
		if(this.tabID==wlID){
			callback(holdings);
		}
	},
	_getTabData:function(){
		var wl_alias='',d = [],wl_info={};
		if(this.profile.openedList.length > 0){
			for (var i = 0,l=this.profile.openedList.length; i < l; i++) {
				wl_alias=this.profile.openedList[i];
				wl_info=this._getWatchlistInfo(wl_alias);
				d .push({
					txt: wl_info.name,
					id: wl_alias,
					decimal : wl_info.decimal,
					closable:this.profile.tabclosable
				});
			}
		}else{
			wl_info=this._getWatchlistInfo(this.profile.defaultWatchlist);
			d .push({
					txt: wl_info.name,
					id: this.profile.defaultWatchlist,
					decimal : wl_info.decimal
				});
		}
		return d;
	},
	_getWatchlistInfo:function(id){
		if(!this.cacheWL[id]){
			this.cacheWL[id]={};
			if(typeof MstarData!='undefined'&&MstarData.Watchlist[id]){
				this.cacheWL[id]=MstarData.Watchlist[id];
			}else{
				Util.message("MstarData.Watchlist don't this watchlist["+id+"] config.");
			}
		}
		return this.cacheWL[id];
	},
	updateData:function(gKey,needupdatefiled){
        this.tickerlist.updateData(gKey,needupdatefiled);
    },
	setColumnsByKeys:function(keys){
		var newKeys=[];
		for(var i=0,l=keys.length;i<l;i++){
			newKeys.push({"dataIndex":keys[i]});
		}
		this.tickerlist.setColumnsByKeys(newKeys);
	},
	_getDBWLlist: function(callback){
        var self=this;
		DBHelper.getDefaultWatchlist(function(data){
			if(data&&data!="error"){
				var jData = $.evalJSON(data);
				if(jData&&jData.list){
					for(var i=0,l=jData.list.length;i<l;i++){
						var PfId=jData.list[i].watchId;
						if(!self.cacheWL[PfId]){
							self.cacheWL[PfId]={};
						}
						self.cacheWL[PfId].name = jData.list[i].watchName;
						if(jData.list[i].groupName){
							self.cacheWL[PfId].type = jData.list[i].groupName; 
						}
						if(jData.list[i].securityType){
							self.cacheWL[PfId].securityType	 = 	jData.list[i].securityType;	
						}	
						self.cacheWL[PfId].inDB=true;					
					}
				}
			}
			callback();
		});
    },
	changeOutSize:function(w,h){
		if(this.profile.isAPI){
    		w = this.profile.width||w||this.container.width();
    		h = this.profile.height||h||this.container.height();
        }else{
            //if it is terminal, the height of win-bd is static
            w = w||this.container.parent().width();
            h = h||this.container.parent().height();
            this.el.css({
                width: "auto"
            });
        }
        w =Math.max(this.staticValue.minWidth,w);
		this.tickerlist.changeOutSize(w,h-(this.profile.showTab?this.staticValue.tabMenuHeight:0)-(this.bottomTextShow?this.staticValue.bottomTextHeight:0));
	}
};
